package com.panda.business.service;

import com.panda.business.domain.AccountInfo;
import com.panda.common.core.domain.entity.SysUser;
import com.panda.common.core.domain.model.LoginUser;
import com.panda.common.exception.CustomException;
import com.panda.common.exception.user.UserPasswordNotMatchException;
import com.panda.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional // 支持事务
public class AccountService {

	@Autowired
	private ISysUserService accountMapper;

	@Resource
	private AuthenticationManager authenticationManager;


	public AccountInfo findAccountInfoByid(long id) {
		SysUser user = accountMapper.selectUserById(id);
		AccountInfo result= new AccountInfo(user);
		return result;
	}
	
	public AccountInfo findAccountInfoByWeChatId(String  wechatId) {
		SysUser user = accountMapper.findAccountInfoByWeChatId(wechatId);
		AccountInfo result= new AccountInfo(user);
		return result;
	}
	 
	public AccountInfo findAccountInfoByAccount(String account) {
		SysUser user = accountMapper.findAccountInfoByAccount(account);
		AccountInfo result= new AccountInfo(user);
		return result;
	}
	 
	public List<AccountInfo> getAllAccountInfoByCid(){
		List<SysUser> allAccountInfoByCid = accountMapper.getAllAccountInfoByCid();
		List<AccountInfo> result= new ArrayList<>();
		allAccountInfoByCid.forEach(item->result.add(new AccountInfo(item)));
		return result;
	}

	
	public AccountInfo clientlogin(String loginname,String password) {
		// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
		// 用户验证
		Authentication authentication = null;
		try
		{
			// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
			authentication = authenticationManager
					.authenticate(new UsernamePasswordAuthenticationToken(loginname, password));
		}
		catch (Exception e)
		{
			if (e instanceof BadCredentialsException)
			{
				throw new UserPasswordNotMatchException();
			}
			else
			{
				throw new CustomException(e.getMessage());
			}
		}
		LoginUser loginUser = (LoginUser) authentication.getPrincipal();
		if(loginUser ==null||loginUser.getUser()==null){
			return null;
		}
		return new AccountInfo(loginUser.getUser());
	}
	

}
